<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

namespace Util;

/**
 * ThinkPHP 数据库中间层实现类
 */
class Db {

    static private  $instance   =  array();     //  数据库连接实例
    static private  $_instance  =  null;   //  当前数据库连接实例

    /**
     * 取得数据库类实例
     * @static
     * @access public
     * @param mixed $config 连接配置
     * @return Object 返回数据库驱动类
     */
    static public function getInstance($config=array()) {
        $md5    =   md5(serialize($config));
        if(!isset(self::$instance[$md5])) {
            // 解析连接参数 支持数组和字符串
            $options    =   self::parseConfig($config);
            // 兼容mysqli
            if('mysqli' == $options['type']) $options['type']   =   'mysql';
            // 如果采用lite方式 仅支持原生SQL 包括query和execute方法
            $class  =   'Util\\Db\\Driver\\'.ucwords($options['type']);

            if(class_exists($class)){
                self::$instance[$md5]   =   new $class($options);
            }else{
                // 类没有定义
                throw new \Exception('没有数据库驱动'.': ' . $class);
            }
        }
        self::$_instance    =   self::$instance[$md5];
        return self::$_instance;
    }

    /**
     * 数据库连接参数解析
     * @static
     * @access private
     * @param mixed $config
     * @return array
     */
    //读取数据库配置信息
    static private function parseConfig($db_config='') {
        if ( !empty($db_config) && is_string($db_config)) {
            // 如果DSN字符串则进行解析
            $db_config = $this->parseDSN($db_config);
        }elseif(is_array($db_config)) { // 数组配置
             $db_config = array(
                  'type'        => $db_config['db_type'],
                  'username'  => $db_config['db_user'],
                  'password'   => $db_config['db_pwd'],
                  'hostname'  => $db_config['db_host'],
                  'hostport'    => $db_config['db_port'],
                  'database'   => $db_config['db_name'],
                  'dsn'         => $db_config['db_dsn'],
                  'params'   => $db_config['db_params'],
             );
        }elseif(empty($db_config)) {
            // 如果配置为空，读取配置文件设置
            $Conf = config('db');
            if( $Conf['db_dsn'] && 'pdo' != strtolower($Conf['db_type']) ) { // 如果设置了DB_DSN 则优先
                $db_config =  self::parseDSN($Conf['DB_DSN']);
            }else{
                $db_config = array (
                    'type'        =>   $Conf['db_type']?$Conf['db_type']:'mysql',
                    'username'  =>   $Conf['user'],
                    'password'   =>   $Conf['pass'],
                    'hostname'  =>   $Conf['host'],
                    'hostport'    =>   $Conf['port'],
                    'database'   =>   $Conf['db'],
                    'dsn'          =>   $Conf['db_dsn'],
                    'params'     =>   $Conf['db_params'],
                    'charset'    => $Conf['db_charset']?$Conf['db_charset']:'utf8'
                );
            }
        }
        return $db_config;
    }

    /**
     * DSN解析
     * 格式： mysql://username:passwd@localhost:3306/DbName?param1=val1&param2=val2#utf8
     * @static
     * @access private
     * @param string $dsnStr
     * @return array
     */
    static private function parseDsn($dsnStr) {
        if( empty($dsnStr) ){return false;}
        $info = parse_url($dsnStr);
        if(!$info) {
            return false;
        }
        $dsn = array(
            'type'      =>  $info['scheme'],
            'username'  =>  isset($info['user']) ? $info['user'] : '',
            'password'  =>  isset($info['pass']) ? $info['pass'] : '',
            'hostname'  =>  isset($info['host']) ? $info['host'] : '',
            'hostport'  =>  isset($info['port']) ? $info['port'] : '',
            'database'  =>  isset($info['path']) ? substr($info['path'],1) : '',
            'charset'   =>  isset($info['fragment'])?$info['fragment']:'utf8',
        );
        
        if(isset($info['query'])) {
            parse_str($info['query'],$dsn['params']);
        }else{
            $dsn['params']  =   array();
        }
        return $dsn;
     }

    // 调用驱动类的方法
    static public function __callStatic($method, $params){
        return call_user_func_array(array(self::$_instance, $method), $params);
    }
}
